package com.zl.gmadmin.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Objects;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/2/2 11:49
 */
public class JsonUtil {

    /**
     * 定义jackson对象
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String toJsonStr(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 45      * 将json结果集转化为对象
     * 46      *
     * 47      * @param jsonData json数据
     * 48      * @param beanType 对象中的object类型
     * 49      * @return
     * 50
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 62      * 将json数据转换成pojo对象list
     * 63      * <p>Title: jsonToList</p>
     * 64      * <p>Description: </p>
     * 65      *
     * 66      * @param jsonData
     * 67      * @param beanType
     * 68      * @return
     * 69
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
